package leetcode.array.reverse;

import java.util.Arrays;

/**
 * 189.轮转数组
 */
public class Rotate {

    public static void main(String[] args) {
        Rotate solution = new Rotate();
        int[] num = new int[]{-1, -100, 3, 99};
        solution.rotate(num, 2);
        System.out.println(Arrays.toString(num));
    }

    public void rotate(int[] nums, int k) {
        int n = nums.length;
        k %= n; // 轮转k次等于轮转k%n次
        // 反转整个数组
        reverse(nums, 0, n - 1);
        // 反转前k个
        reverse(nums, 0, k - 1);
        // 反转后n-k个
        reverse(nums, k, n - 1);
    }


    /**
     * 反转数组
     */
    private void reverse(int[] nums, int i, int j) {
        while (i < j) {
            int temp = nums[i];
            nums[i++] = nums[j];
            nums[j--] = temp;
        }
    }
}
